import React from 'react';
import { connect } from 'react-redux';
import { Row, Col, Card, Tooltip } from 'antd';
import NameListList from './list';
import CommonListsIndex from '../../../../components/CommonLists/index';
import FilterTool from '../../../../components/FilterTool';
import services from '../../../../services/api';
import { message, Button } from 'antd';
import { compare } from '../../../../utils/compare';
import { ENABLE_STATUS } from '../../../../utils/constant';
import CodeLabel from '../../../../components/CodeLabel';
import { isEqual, cloneDeep } from 'lodash';

function mapStateToProps(state) {
  return {
    namelist_type: state.code.namelist_type,
    namelist_data_type: state.code.namelist_data_type,
    depts: state.global.depts,
  };
}

@connect(mapStateToProps)
class NameListIndex extends CommonListsIndex {
  constructor(props) {
    super(props);
    this.api = 'nameListDetail';
    this.listsComponent = NameListList;
    this.model_width = '500px';
    this.queryParams = {};
    this.queryPanigation = {
      current_page: 1,
      page_size: 10,
    };
    this.queryTableParams = {};
    this.state = {
      list: [],
      totalCount: 0,
      detail: {},
      name_list_id: (props.match && props.match.params && props.match.params.id) || '',
      namelist_type: {},
      namelist_data_type: {},
    };
    this.allDeptIds = props.depts.map((item) => item.dept_id);
  }

  componentWillMount() {
    if (!this.props.namelist_data_type) {
      const interval = setInterval(() => {
        if (this.props.namelist_data_type) {
          const namelist_type = {};
          this.props.namelist_type.forEach((item) => {
            namelist_type[item.id] = item.value;
          });
          const namelist_data_type = {};
          this.props.namelist_data_type.forEach((item) => {
            namelist_data_type[item.id] = item.value;
          });
          this.setState({
            namelist_type,
            namelist_data_type,
          });
          clearInterval(interval);
        }
      }, 50);
    } else {
      const namelist_type = {};
      this.props.namelist_type.forEach((item) => {
        namelist_type[item.id] = item.value;
      });
      const namelist_data_type = {};
      this.props.namelist_data_type.forEach((item) => {
        namelist_data_type[item.id] = item.value;
      });
      this.setState({
        namelist_type,
        namelist_data_type,
      });
    }
    if (this.state.name_list_id) {
      services.nameList.detail({ name_list_id: this.state.name_list_id }).then((res) => {
        if (res.code === 0) {
          const detail = cloneDeep(res.data);
          isEqual(this.allDeptIds, detail.dept_ids) && (detail.dept_names = ['全部']);
          this.setState({
            detail,
          });
        }
      });
    } else {
      const detail = cloneDeep(this.props.value);
      isEqual(this.allDeptIds, detail.dept_ids) && (detail.dept_names = ['全部']);
      this.setState({
        detail,
        list: this.props.value.name_list_data,
      });
    }
  }

  refreshTableFilter = (params) => {
    (Object.keys(params)).forEach(item => {
      if (params[item] === -1) params[item] = undefined
    })
    this.queryTableParams = { ...this.queryTableParams, ...params };
    this.refreshPanagaition(this.initQueryPanigation);
    this.freshQueryList();
  };

  queryList(params) {
    if (this.state.name_list_id) {
      params.name_list_id = this.state.name_list_id;
      services[this.api].list(params).then((res) => {
        if (res.code === 0) {
          const { list, totalCount } = res.data
          const currentPage = params.current_page
          const page = Math.ceil(totalCount / this.queryPanigation.page_size)
          if (list && totalCount && list.length === 0 && currentPage > page) {
            this.onChangePagination(page, 'current_page')
          } else {
            this.setState({
              ...res.data,
            });
          }
          // this.setState({
          //   ...res.data,
          // });
        } else {
          message.error(res.msg);
        }
      });
    }
  }
  freshQueryList = () => {
    this.queryList({ ...this.queryPanigation, ...this.queryTableParams, ...this.queryParams });
  };
  refreshPanagaition = (params) => {
    this.queryPanigation = {
      ...this.queryPanigation,
      ...params,
    };
  };
  refreshFilter = (params, type) => {
    this.queryParams = params;
    if (type === false) return
    this.freshQueryList(this.queryParams);
  };

  getColumns = () => {
    return [
      {
        title: '名单数据',
        key: 'data_content',
        dataIndex: 'data_content',
        ellipsis: true,
        render: (text, record, index) => {
          return (
            <div style={compare(this.props, 'name_list_data', index, 'data_content')}>
              {record.type === 2 ? (
                <Tooltip title={text} placement='topLeft'>
                  <div className="overflowtext">
                    <Button type='link' onClick={() => this.props.showDetail(record)}>
                      {text}
                    </Button>
                  </div>
                </Tooltip>
              ) : (
                <Tooltip title={text} placement='topLeft'>
                  {text}
                </Tooltip>
              )}
            </div>
          );
        },
      },
      {
        title: '有效期始',
        key: 'start_time',
        dataIndex: 'start_time',
        render: (text, record, index) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              <span style={compare(this.props, 'name_list_data', index, 'start_time')}>{text}</span>
            </Tooltip>
          );
        },
      },
      {
        title: '有效期止',
        key: 'end_time',
        dataIndex: 'end_time',
        render: (text, record, index) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              <span style={compare(this.props, 'name_list_data', index, 'end_time')}>{text}</span>
            </Tooltip>
          );
        },
      },
      {
        title: '备注',
        key: 'remark',
        dataIndex: 'remark',
        render: (text, record, index) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              <span style={compare(this.props, 'name_list_data', index, 'remark')}>{text}</span>
            </Tooltip>
          );
        },
      },

      (this.props.isCompare || this.props.isAuditLog)
        ? false
        : {
            title: '创建/修改人',
            key: 'create_user_name',
            dataIndex: 'create_user_name',
            render: (_, record) => {
              return (
                <Tooltip title={`${record.create_user_name}/${record.update_user_name}`} placement='topLeft'>{`${
                  record.create_user_name
                }/${record.update_user_name}`}</Tooltip>
              );
            },
          },
      (this.props.isCompare || this.props.isAuditLog)
        ? false
        : {
            title: '修改时间',
            key: 'update_time',
            dataIndex: 'update_time',
            render: (text) => {
              return (
                <Tooltip title={text} placement='topLeft'>
                  <div className='overflowtext'>{text}</div>
                </Tooltip>
              );
            },
          },
      (this.props.isCompare || this.props.isAuditLog)
        ? false
        : {
            title: '审核情况',
            key: 'audit_label',
            dataIndex: 'audit_label',
            render: (text) => {
              return (
                <Tooltip title={text} placement='topLeft'>
                  <div className='overflowtext'>{text}</div>
                </Tooltip>
              );
            },
          },
      {
        title: (this.props.isCompare || this.props.isAuditLog) ? (
          '状态'
        ) : (
          <>
            {this.getFilterTitle(
              '状态',
              [
                {
                  value: 1,
                  name: '启用',
                },
                {
                  value: 2,
                  name: '停用',
                },
              ],
              'status',
              this.refreshTableFilter,
              ['value', 'name']
            )}
          </>
        ),
        key: 'status',
        dataIndex: 'status',
        render: (_, record, index) => {
          return (
            <span style={compare(this.props, 'name_list_data', index, 'status')}>
              {record.status === ENABLE_STATUS._TRUE ? '启用' : '停用'}
            </span>
          );
        },
        ellipsis: true,
        width: 100,
      },
    ].filter(Boolean);
  };

  render() {
    const ListsComponent = this.listsComponent;
    const data = [
      {
        type: 'Search',
        key: 'keyword',
        name: 'keyword',
        defaultValue: '',
        placeholder: '请输入名单数据或备注关键字',
      },
    ];
    return (
      <div className='tantuer-form' style={{ marginTop: '20px' }}>
        <Card>
          <Row type='flex' style={{ lineHeight: '3' }} gutter={100}>
            <Col>
              <div className='tantuer-form-item2'>
                <div className='ant-form-item-label'>
                  <label>名单名称</label>
                </div>
                <span style={compare(this.props, 'list_name')}>{this.state.detail.list_name}</span>
              </div>
              <div className='tantuer-form-item2'>
                <div className='ant-form-item-label'>
                  <label>数据类型</label>
                </div>
                <span style={compare(this.props, 'data_type')}>
                  <CodeLabel code='namelist_data_type' value={this.state.detail.data_type} />
                </span>
              </div>
              <div className='tantuer-form-item2'>
                <div className='ant-form-item-label'>
                  <label>状态</label>
                </div>
                <span style={compare(this.props, 'status')}>
                  {this.state.detail.status === ENABLE_STATUS._TRUE ? '启用' : '停用'}
                </span>
              </div>
            </Col>
            <Col>
              <div className='tantuer-form-item2'>
                <div className='ant-form-item-label'>
                  <label>名单类型</label>
                </div>
                <span style={compare(this.props, 'list_type')}>
                  <CodeLabel code='namelist_type' value={this.state.detail.list_type} />
                </span>
              </div>
              <div className='tantuer-form-item2'>
                <div className='ant-form-item-label'>
                  <label>可见部门</label>
                </div>
                <span style={compare(this.props, 'dept_ids')}>
                  {this.state.detail.dept_names && this.state.detail.dept_names.join(',')}
                </span>
              </div>
              <div className='tantuer-form-item2'>
                <div className='ant-form-item-label'>
                  <label>描述</label>
                </div>
                <span style={compare(this.props, 'remark')}>{this.state.detail.remark}</span>
              </div>
            </Col>
          </Row>
        </Card>
        {this.props.isCompare ? null : (
          <Row type='flex' justify='end' align='middle' style={{ marginTop: '10px' }}>
            <Col>
              <FilterTool
                data={data}
                colNum={1}
                query={this.freshQueryList}
                refreshFilter={this.refreshFilter}
                isOnChange={true}
                refresh={this.resetList}
              />
            </Col>
          </Row>
        )}
        <div className='inner-content' style={{ marginTop: '10px' }}>
          <ListsComponent
            {...this.state}
            edit={this.edit}
            onChangePagination={this.onChangePagination}
            showDetail={this.showDetail}
            columns={this.getColumns()}
            rowKey='name_list_data_id'
          />
        </div>
      </div>
    );
  }
}

export default NameListIndex;
